package rsj.service.usage;

import com.alibaba.fastjson.JSON;
import com.rlyy.aibase.db.QueryRunner;
import com.rlyy.aibase.utils.base.*;
import common.exec.RsjIllegalArgueException;
import common.util.QueryRunnerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import rsj.api.org.entity.CurrentTableColumn;
import rsj.api.org.entity.ExportParam;
import rsj.api.org.entity.UsageReportParam;
import rsj.util.HumpToLineUtil;
import common.util.validator.ParameterConversionCheck;

import java.util.List;

/**
 * 列表查询模板方法接口（直接调用usageReport()方法，子类实现具体查询逻辑）
 *
 * @author yuanqinglong
 * @since 2021/3/4 9:21
 */
public interface IUsageTemplateMethod extends ICalculateUsage {
    Logger logger = LoggerFactory.getLogger(IUsageTemplateMethod.class);

    QueryRunner QUERY_RUNNER = QueryRunnerFactory.getQueryRunner();
    /**
     * 测试环境
     */
    String TEST_ENVIRONMENT = "01";
    /**
     * 生产环境
     */
    String PRODUCE_ENVIRONMENT = "02";
    /**
     * 线下测试环境
     */
    String OFFLINE_ENVIRONMENT = "03";


    /**
     * 查询-使用情况
     *
     * @param in         参数
     * @param statEnv    环境（01：测试环境，02：生产环境，03：线下测试环境）
     * @param checkGroup 参数校验组（ByProduct.class：产品管理验证statProdId，ByOrg.class：机构管理验证statOrgId）
     * @return 使用情况
     */
    default MapNode usageReport(Box in, String statEnv, Class<?>... checkGroup) {
        MapNode responseData;
        try {
            UsageReportParam usageReportParam = (UsageReportParam) ParameterConversionCheck.parameterConversionCheckFastFail(in, UsageReportParam.class, checkGroup);
            usageReportParam.setEnvironment(statEnv);
            Node node = this.countStatistic(usageReportParam);
            TableNode tableNode = this.queryTableByPage(usageReportParam);
            List<CurrentTableColumn> statisticColumnEntities = JSON.parseArray(tableNode.toJson(), CurrentTableColumn.class);
            if (!CollectionUtils.isEmpty(statisticColumnEntities)) {
                // 处理接口的使用量分组累计
//                this.queryInterfaceUsageThroughContract(statisticColumnEntities, connection, statEnv, usageReportParam);
                // 计算剩余量
                this.ifYouNeedToCalculateTheRemainingAmount(statisticColumnEntities);
            }
            String conversionField = HumpToLineUtil.conversionField(JSON.toJSONString(statisticColumnEntities));
            responseData = new MapNode().putNode("List", conversionField).putNode("Count", node.value());
        } catch (ThinkException e) {
            logger.error("IUsageTemplateMethod列表查询异常，参数:{}", in.toJson(), e);
            throw new RsjIllegalArgueException("查询异常");
        }
        return responseData;
    }


    /**
     * 数统计
     *
     * @param usageReportParam 参数
     * @return {@link Node}
     */
    default Node countStatistic(UsageReportParam usageReportParam) {
        return new Node();
    }


    /**
     * 导出产品当前表
     *
     * @param usageReportParam 参数
     * @return {@link TableNode}
     */
    default TableNode queryTableByPage(UsageReportParam usageReportParam) {
        return new TableNode();
    }




    /**
     * 生成查询sql
     *
     * @param usageReportParam 参数
     * @return sql
     */
    String generateQueryStatement(UsageReportParam usageReportParam);

    /**
     * 生成统计个数sql
     *
     * @param usageReportParam 参数
     * @return sql
     */
    String generateCountStatement(UsageReportParam usageReportParam);


    /**
     * 转换参数实体
     *
     * @param usageReportParam 使用情况报告参数
     * @param statEnv          stat env
     * @return {@link ExportParam}
     */
    default ExportParam conversionParameterEntity(UsageReportParam usageReportParam, String statEnv) {
        return new ExportParam(usageReportParam.getStatOrgId(), usageReportParam.getStatProdUid(),
                usageReportParam.getStatOrgpId(), usageReportParam.getStatDate(), usageReportParam.getPageInfo().getPageSize(), usageReportParam.getPageInfo().getPageNow(), statEnv);
    }
}
